import { users, products, orders, chartData, menus, departments, roles, dictionaries } from '../mock/data';

// 模拟API请求延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 用户相关服务
export const userService = {
  // 获取用户列表
  async getUsers() {
    await delay(500);
    return users;
  },

  // 获取单个用户
  async getUser(id) {
    await delay(500);
    return users.find(user => user.id === id);
  },

  // 创建用户
  async createUser(userData) {
    await delay(500);
    const newUser = {
      id: users.length + 1,
      ...userData,
      status: userData.status || 'active'
    };
    users.push(newUser);
    return newUser;
  },

  // 更新用户
  async updateUser(id, userData) {
    await delay(500);
    const index = users.findIndex(user => user.id === id);
    if (index !== -1) {
      users[index] = { ...users[index], ...userData };
      return users[index];
    }
    return null;
  },

  // 删除用户
  async deleteUser(id) {
    await delay(500);
    const index = users.findIndex(user => user.id === id);
    if (index !== -1) {
      return users.splice(index, 1)[0];
    }
    return null;
  },

  // 用户登录
  async login(credentials) {
    await delay(500);
    const user = users.find(
      user => user.username === credentials.username && user.password === credentials.password
    );
    if (user) {
      return {
        success: true,
        token: `fake-token-${user.id}`,
        user: {
          id: user.id,
          username: user.username,
          role: user.role
        }
      };
    }
    return {
      success: false,
      message: '用户名或密码错误'
    };
  }
};

// 订单相关服务
const orderService = {
  // 获取订单列表
  async getOrders() {
    await delay(500);
    return orders;
  },

  // 获取单个订单
  async getOrder(id) {
    await delay(500);
    return orders.find(order => order.id === id);
  },

  // 创建订单
  async createOrder(orderData) {
    await delay(500);
    const newOrder = {
      id: orders.length + 1,
      ...orderData,
      orderNumber: `ORD-${Date.now().toString().slice(-6)}`,
      createdAt: new Date().toISOString(),
      status: 'pending'
    };
    orders.push(newOrder);
    return newOrder;
  },

  // 更新订单
  async updateOrder(id, orderData) {
    await delay(500);
    const index = orders.findIndex(order => order.id === id);
    if (index !== -1) {
      orders[index] = { ...orders[index], ...orderData };
      return orders[index];
    }
    return null;
  },

  // 删除订单
  async deleteOrder(id) {
    await delay(500);
    const index = orders.findIndex(order => order.id === id);
    if (index !== -1) {
      return orders.splice(index, 1)[0];
    }
    return null;
  }
};

// 导出服务

export const { getUsers, getUser, createUser, updateUser, deleteUser, login } = userService;
export const { getOrders, getOrder, createOrder, updateOrder, deleteOrder } = orderService;

// 数据报表服务
const reportService = {
  // 获取图表数据
  async getChartData() {
    await delay(500);
    return chartData;
  }
};

export const { getChartData } = reportService;

// 系统设置服务
const settingsService = {
  // 获取用户配置
  async getUserProfile() {
    await delay(500);
    return {
      username: '管理员',
      email: 'admin@example.com',
      phone: '13800138000'
    };
  },

  // 更新用户配置
  async updateUserProfile(profileData) {
    await delay(500);
    return profileData;
  },

  // 获取系统设置
  async getSystemSettings() {
    await delay(500);
    return {
      notifications: true,
      emailNotifications: true,
      theme: 'light',
      language: 'zh-CN'
    };
  },

  // 更新系统设置
  async updateSystemSettings(settingsData) {
    await delay(500);
    return settingsData;
  }
};

export const { getUserProfile, updateUserProfile, getSystemSettings, updateSystemSettings } = settingsService;

// 用户登录已移至userService中

// 服务相关服务
const serviceService = {
  // 获取服务列表
  async getServices() {
    await delay(500);
    // 在实际应用中，这里应该返回服务列表
    // 为了快速修复，我们暂时使用产品数据
    return products.map(product => ({
      ...product,
      // 可以根据需要调整字段名称
      serviceName: product.name,
      servicePrice: product.price
    }));
  },

  // 获取单个服务
  async getService(id) {
    await delay(500);
    const product = products.find(product => product.id === id);
    if (product) {
      return {
        ...product,
        serviceName: product.name,
        servicePrice: product.price
      };
    }
    return null;
  },

  // 创建服务
  async createService(serviceData) {
    await delay(500);
    const newService = {
      id: products.length + 1,
      ...serviceData,
      createdAt: new Date().toISOString()
    };
    products.push(newService);
    return newService;
  },

  // 更新服务
  async updateService(id, serviceData) {
    await delay(500);
    const index = products.findIndex(product => product.id === id);
    if (index !== -1) {
      products[index] = { ...products[index], ...serviceData };
      return {
        ...products[index],
        serviceName: products[index].name,
        servicePrice: products[index].price
      };
    }
    return null;
  },

  // 删除服务
  async deleteService(id) {
    await delay(500);
    const index = products.findIndex(product => product.id === id);
    if (index !== -1) {
      const deletedProduct = products.splice(index, 1)[0];
      return {
        ...deletedProduct,
        serviceName: deletedProduct.name,
        servicePrice: deletedProduct.price
      };
    }
    return null;
  }
};

export const { getServices, getService, createService, updateService, deleteService } = serviceService;

// 菜单相关服务
const menuService = {
  // 获取菜单列表
  async getMenus() {
    await delay(500);
    return menus;
  },

  // 获取单个菜单
  async getMenu(id) {
    await delay(500);
    return menus.find(menu => menu.id === id);
  },

  // 创建菜单
  async createMenu(menuData) {
    await delay(500);
    const newMenu = {
      id: menus.length + 1,
      ...menuData,
      sort: menuData.sort || 0
    };
    menus.push(newMenu);
    return newMenu;
  },

  // 更新菜单
  async updateMenu(id, menuData) {
    await delay(500);
    const index = menus.findIndex(menu => menu.id === id);
    if (index !== -1) {
      menus[index] = { ...menus[index], ...menuData };
      return menus[index];
    }
    return null;
  },

  // 删除菜单
  async deleteMenu(id) {
    await delay(500);
    const index = menus.findIndex(menu => menu.id === id);
    if (index !== -1) {
      // 同时删除子菜单
      const deletedMenu = menus.splice(index, 1)[0];
      const children = menus.filter(menu => menu.parentId === id);
      children.forEach(child => this.deleteMenu(child.id));
      return deletedMenu;
    }
    return null;
  }
};

export const { getMenus, getMenu, createMenu, updateMenu, deleteMenu } = menuService;

// 部门相关服务
const departmentService = {
  // 获取部门列表
  async getDepartments() {
    await delay(500);
    return departments;
  },

  // 获取单个部门
  async getDepartment(id) {
    await delay(500);
    return departments.find(dept => dept.id === id);
  },

  // 创建部门
  async createDepartment(deptData) {
    await delay(500);
    const newDept = {
      id: departments.length + 1,
      ...deptData
    };
    departments.push(newDept);
    return newDept;
  },

  // 更新部门
  async updateDepartment(id, deptData) {
    await delay(500);
    const index = departments.findIndex(dept => dept.id === id);
    if (index !== -1) {
      departments[index] = { ...departments[index], ...deptData };
      return departments[index];
    }
    return null;
  },

  // 删除部门
  async deleteDepartment(id) {
    await delay(500);
    const index = departments.findIndex(dept => dept.id === id);
    if (index !== -1) {
      // 同时删除子部门
      const deletedDept = departments.splice(index, 1)[0];
      const children = departments.filter(dept => dept.parentId === id);
      children.forEach(child => this.deleteDepartment(child.id));
      return deletedDept;
    }
    return null;
  }
};

export const { getDepartments, getDepartment, createDepartment, updateDepartment, deleteDepartment } = departmentService;

// 角色相关服务
const roleService = {
  // 获取角色列表
  async getRoles() {
    await delay(500);
    return roles;
  },

  // 获取单个角色
  async getRole(id) {
    await delay(500);
    return roles.find(role => role.id === id);
  },

  // 创建角色
  async createRole(roleData) {
    await delay(500);
    const newRole = {
      id: roles.length + 1,
      ...roleData,
      menuIds: roleData.menuIds || []
    };
    roles.push(newRole);
    return newRole;
  },

  // 更新角色
  async updateRole(id, roleData) {
    await delay(500);
    const index = roles.findIndex(role => role.id === id);
    if (index !== -1) {
      roles[index] = { ...roles[index], ...roleData };
      return roles[index];
    }
    return null;
  },

  // 删除角色
  async deleteRole(id) {
    await delay(500);
    const index = roles.findIndex(role => role.id === id);
    if (index !== -1) {
      return roles.splice(index, 1)[0];
    }
    return null;
  }
};

export const { getRoles, getRole, createRole, updateRole, deleteRole } = roleService;

// 字典相关服务
const dictionaryService = {
  // 获取字典列表
  async getDictionaries() {
    await delay(500);
    return dictionaries;
  },

  // 获取单个字典
  async getDictionary(id) {
    await delay(500);
    return dictionaries.find(dict => dict.id === id);
  },

  // 创建字典
  async createDictionary(dictData) {
    await delay(500);
    const newDict = {
      id: dictionaries.length + 1,
      ...dictData,
      items: dictData.items || []
    };
    dictionaries.push(newDict);
    return newDict;
  },

  // 更新字典
  async updateDictionary(id, dictData) {
    await delay(500);
    const index = dictionaries.findIndex(dict => dict.id === id);
    if (index !== -1) {
      dictionaries[index] = { ...dictionaries[index], ...dictData };
      return dictionaries[index];
    }
    return null;
  },

  // 删除字典
  async deleteDictionary(id) {
    await delay(500);
    const index = dictionaries.findIndex(dict => dict.id === id);
    if (index !== -1) {
      return dictionaries.splice(index, 1)[0];
    }
    return null;
  }
};

export const { getDictionaries, getDictionary, createDictionary, updateDictionary, deleteDictionary } = dictionaryService;

// 产品相关服务（保留以兼容现有代码）
export const productService = {
  // 获取产品列表
  async getProducts() {
    await delay(500);
    return products;
  },

  // 获取单个产品
  async getProduct(id) {
    await delay(500);
    return products.find(product => product.id === id);
  },

  // 创建产品
  async createProduct(productData) {
    await delay(500);
    const newProduct = {
      id: products.length + 1,
      ...productData,
      status: productData.status || 'active'
    };
    products.push(newProduct);
    return newProduct;
  },

  // 更新产品
  async updateProduct(id, productData) {
    await delay(500);
    const index = products.findIndex(product => product.id === id);
    if (index !== -1) {
      products[index] = { ...products[index], ...productData };
      return products[index];
    }
    return null;
  },

  // 删除产品
  async deleteProduct(id) {
    await delay(500);
    const index = products.findIndex(product => product.id === id);
    if (index !== -1) {
      return products.splice(index, 1)[0];
    }
    return null;
  }
};

// 注意：orderService和chartService已在文件上方定义并导出
// 如需使用订单服务，请使用：import { getOrders, getOrder, createOrder, updateOrder, deleteOrder } from '../services/api';
// 如需使用图表服务，请使用：import { getChartData } from '../services/api';

export const { getProducts, getProduct, createProduct, updateProduct, deleteProduct } = productService;

// 导出服务别名，确保兼容性
// export const getServices = getProducts; // 可选：如果只是重命名而不修改实现

// 产品相关服务已移至文件上方